import Markdown from 'markdown-to-jsx'
import Highlight from 'react-highlight'
import 'highlight.js/styles/github.css'; // 导入默认样式
import { memo, useMemo, useState } from 'react';
import 'highlight.js/styles/atom-one-dark.css'


const CodeBlock = ({ children, className }) => {

    const language = useMemo(() => {
        if (!className) return 'javascript';
        // 支持 language- 和 lang- 前缀
        return className.replace(/^(language-|lang-)/, '') || 'javascript';
    }, [className]);

    const isInlineCode = () => {
        if (typeof children !== 'string') return false;
        return !children.includes('\n') &&
            !className?.match(/(language-|lang-)/) && // 修改检测逻辑
            children.length < 50;
    };

    if (isInlineCode()) {
        return (
            <span className="bg-[#F9F9F9] px-2 py-1 rounded text-sm font-mono"
                style={{
                    border: '1px solid #eaeaea', borderRadius: '4px',
                    padding: '0.2em 0.4em', fontSize: '85%',
                    fontFamily: 'monospace'
                }}
            >
                <code className={className}>{children}</code>
            </span>
        );
    }

    const [copyStatus, setCopyStatus] = useState('复制代码');

    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(children);
            setCopyStatus('已复制!');
            setTimeout(() => setCopyStatus('复制代码'), 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
        }
    };

    return (
        <div className="bg-[#282C34] mb-2 mt-2 rounded-xl overflow-x-auto max-w-[800px]">
            <div className='text-[#ABB2BF] p-4 pb-2 pt-2 bg-[#383d48]'>
                <span>{language}</span>
                <button
                    onClick={handleCopy}
                    className="ml-4 px-2 py-1 text-sm text-[#ABB2BF] hover:bg-[#4B5263] rounded transition-colors">
                    {copyStatus}
                </button>
            </div>
            <div className='p-4'>
                <Highlight className={language}>
                    {children}
                </Highlight>
            </div>
        </div>
    );
};


// 定义带边框样式的表格组件
const CustomTable = ({ children }) => (
    <table style={{ border: "1px solid #D9D9D9", borderCollapse: "collapse", width: "100%" }}>
        {children}
    </table>
);

// 定义带边框样式的表格单元格组件
const CustomTd = ({ children }) => (
    <td style={{ border: "1px solid #D9D9D9", padding: "8px" }}>{children}</td>
);

// 自定义样式的标题组件
const CustomH1 = ({ children }) => (
    <h1 style={{ fontWeight: "bold", fontSize: 26 }}>
        {children}
    </h1>
);

const CustomH2 = ({ children }) => (
    <h2 style={{ fontWeight: "bold", fontSize: 22 }}>
        {children}
    </h2>
);

const CustomH3 = ({ children }) => (
    <h3 style={{ fontWeight: "bold", fontSize: 18 }}>
        {children}
    </h3>
);

// 添加自定义的有序列表组件
const CustomOrderedList = ({ children, ...props }) => (
    <ol style={{
        listStyleType: 'decimal',
        paddingLeft: '20px',
        margin: '10px 0'
    }} {...props}>
        {children}
    </ol>
);

// 无序列表组件 (圆点)
const CustomUnorderedList = ({ children, ...props }) => (
    <ul style={{
        listStyleType: 'disc', // 圆点样式
        paddingLeft: '20px',
        margin: '10px 0'
    }} {...props}>
        {children}
    </ul>
);

// 添加自定义的列表项组件
const CustomListItem = ({ children, ...props }) => (
    <li style={{
        margin: '5px 0'
    }} {...props}>
        {children}
    </li>
);

// 添加自定义的图片组件
const CustomImage = ({ src, alt, ...props }) => (
    <img
        src={src}
        alt={alt}
        style={{
            margin: '10px 0',    // 设置图片与其他元素的间距
            borderRadius: '8px', // 设置圆角大小
            maxWidth: '100%',    // 确保图片不会超出容器
            height: 'auto'       // 保持图片比例
        }}
        {...props}
    />
);

const CustomParagraph = ({ children, ...props }) => (
    <p style={{
        margin: '10px 0',
        lineHeight: '1.6'
    }} {...props}>
        {children}
    </p>
);

interface Props {
    markdown: string;
}

const MarkdownRender = (props: Props) => {
    const { markdown } = props

    return (
        <Markdown options={{
            overrides: {
                table: {
                    component: CustomTable,
                },
                td: {
                    component: CustomTd,
                },
                th: {
                    component: CustomTd, // 表头也可以使用自定义样式
                },
                h1: {
                    component: CustomH1,
                },
                h2: {
                    component: CustomH2,
                },
                h3: {
                    component: CustomH3,
                },
                ol: {
                    component: CustomOrderedList,
                },
                ul: {
                    component: CustomUnorderedList
                },
                p: {
                    component: CustomParagraph,
                },
                li: {
                    component: CustomListItem,
                },
                img: {
                    component: CustomImage,
                },
                code: {
                    component: CodeBlock,
                },
            },
        }}>{markdown}</Markdown>
    )
}

export default memo(MarkdownRender)
